package com.example.service.impl;

import com.example.entity.Comment;
import com.example.entity.User;
import com.example.entity.res.CommentRes;
import com.example.mapper.CommentMapper;
import com.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Override
    public List<CommentRes> getCommentsByRecommend(Integer rid) {
        List<Comment> comments = commentMapper.selectCommentFatherByRecommend(rid);
        List<CommentRes> list = new ArrayList<>();
        for (Comment comment : comments) {
            Integer commentid = comment.getCommentid();
            CommentRes commentRes = new CommentRes();
            commentRes.setComment(comment.getComment());
            commentRes.setUserid(comment.getUserid());
            commentRes.setRid(comment.getRid());
            commentRes.setCreattime(comment.getCreattime());
            commentRes.setParentid(0);
            commentRes.setCommentid(commentid);
            List<Comment> listchild = new ArrayList<>();
            List<Comment> finalchildlist = querySubComments(commentid, listchild);
            commentRes.setChildren(finalchildlist);
            list.add(commentRes);
        }
        return list;
    }

    @Override
    public User getUserInfoByParentid(Integer parentid) {
        return commentMapper.getUserInfoByParentid(parentid);
    }

    @Override
    public void addFatherComment(Comment record) {
        commentMapper.insertSelective(record);
    }

    @Override
    public void addChildComment(Comment record) {
        commentMapper.insertSelective(record);
    }

    private List<Comment> querySubComments(Integer parentid, List<Comment> listchild) {
        List<Comment> comments = commentMapper.selectCommentChildrenByParentid(parentid);
        if (comments != null) {
            for (Comment comment : comments) {
                listchild.add(comment);
                querySubComments(comment.getCommentid(), listchild);
            }
        } else {
            return listchild;
        }
        return listchild;
    }
}
